import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)
const originPush = VueRouter.prototype.push
const originReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function(obj,resolved,rejected){
  if(resolved === undefined && rejected === undefined) {
    return originPush.call(this,obj).catch(()=>{})
  }else{
    return originPush.call(this,obj,resolved,rejected)
  }
}
VueRouter.prototype.replace = function(obj,resolved,rejected){
  if(resolved === undefined && rejected === undefined) {
    return originReplace.call(this,obj).catch(()=>{})
  }else{
    return originReplace.call(this,obj,resolved,rejected)
  }
}
const router = new VueRouter({
  mode:'history',
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { y: 0 }
  }
})
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let userInfo = store.state.user.userInfo 
  //如果有用户token,代表用户已经登录
  if(token) {
    //如果已登录,路径又跳转到/login 不让他跳。
    if(to.path == '/login') {
      next('/home')
    }else {
      //如果跳转的别的路径,看是否有userInfo,因为userInfo是个对象，所以要判断里面的属性值
      if(userInfo.name){
        //有userInfo 放行
        next()
      }else {
        try {
          //没有userInfo 重新获取UserInfo
          await store.dispatch('getUserInfo')
          //放行
          next()
        }catch(e) {
          //没有获取成功，删除token 重新登录
          store.dispatch('clearToken')
          next('/login')
        }
      }
    }
  }else {
    if(to.path.indexOf('/trade') === 0 || to.path.indexOf('/pay') === 0 || to.path.startsWith('/paysuccess') || to.path.startsWith('/center')) {
      next(`/login?redirect=${to.path}`)
    }else {
      next()
    }
  }
})
export default router